using System;
using System.Collections.Generic;
using System.Text;

using Mud.Common.Physical;
using Mud.Server.Physical;
using Mud.Server.Users;
using System.Xml;


namespace Mud.Server
{

	/// <summary>
	/// Object responsible for loading/saving objects in the Mud game.
	/// </summary>
	public class ObjectLoader
	{

		private IServer _server;

		public ObjectLoader(IServer server) {
			if (server == null)
				throw new ArgumentNullException("server");
			_server = server;
		}

		/// <summary>
		/// Loads area with specific name.
		/// </summary>
		public Area LoadArea(string areaName) {
            XmlDocument doc = new XmlDocument();
            doc.Load("Data\\Areas\\" + areaName + ".xml");
            int width = int.Parse(doc.SelectSingleNode(@"//Size").Attributes["Width"].Value);
            int height = int.Parse(doc.SelectSingleNode(@"//Size").Attributes["Height"].Value);
            string[] terrain = doc.SelectSingleNode(@"//Terrain").InnerText.Split(new char[] { ' ', '\t', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
 
			Area area = new Area(_server, new Size(width, height));
			area.Name = areaName;
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    area.Land[x, y] = new AreaLandSquare((TerrainType)int.Parse(terrain[x*width + y]));
                }
			}
			return area;
		}

		/// <summary>
		/// Loads player character with specific name.
		/// </summary>
		public Creature LoadCharacter(string characterName) {
			Creature character = new Creature(_server);
			character.PhysicalProperties.Dimensions = new Cube(180, 60, 30);
			character.PhysicalProperties.Mass = 80;
			character.PhysicalProperties.Orientation = Orientation.North;
			character.Sensors = new Sensors(SenseType.All, 20, 5, 5, 0);
            Random random = new Random();
            character.Location = new Location(random.Next(40) + 10, random.Next(40) + 10);
            character.Name = characterName;
            character.CurrentAreaName = "Test area";

			return character;
		}

        /// <summary>
        /// Loads users player characters.
        /// </summary>
        /// <param name="user">Owner of the characters.</param>
        /// <returns>List of characters.</returns>
        public IList<Creature> GetPlayerCharacters(User user)
        {
            List<Creature> characters = new List<Creature>();
            characters.Add(LoadCharacter(user.UserName));
            characters.Add(LoadCharacter(user.UserName + "Maniac"));
            return characters;
        }

	}
}
